package com.woniu.woniu_bx.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Description TODO
 * @Author zhangjin
 * @Date 2022/9/6 20:51
 */
@Slf4j
public class AuthticationFilter extends AbstractAuthenticationProcessingFilter {
    public AuthticationFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        log.debug("进入AuthticationFilter");
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> map = objectMapper.readValue(request.getInputStream(), Map.class);
        String account = map.get("account");
        String password = map.get("password");
        log.debug("Account:{},Password:{}", account, password);
        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(account,
                password);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
